<?php

  if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

  // -- webMS Modification --
  // Check if osCommerce environment is already loaded
  if (defined( '_OSCOMMERCE_LOADED' )) {
    if (!DB_SHARED) {
      // Reconnect to osCommerce Database
      tep_db_connect() or die('Unable to connect to database server!');
    }
    // Load osCommerce Globals for Boxes
    global $category_links, $languages_id, $catID, $catID_array, $current_category_id;
    global $request_type, $lng, $cart, $currencies, $language, $navigation, $breadcrumb;
  } else {
    // Load osCommerce Environment for the First Time
    require('components/'.$option.'/includes/application_top.php');
  }

  if (!tep_session_is_registered('customer_id')) die;

// Check zipdownload.php was called with proper GET parameters
  if ((isset($_REQUEST['order']) && !is_numeric($_REQUEST['order'])) || (isset($_REQUEST['id']) && !is_numeric($_REQUEST['id'])) ) die;
  
// Check that order_id, customer_id and filename match
  $zipdownloads_query = tep_db_query("select date_format(o.date_purchased, '%Y-%m-%d') as date_purchased_day, opzd.download_maxdays, opzd.download_count, opzd.download_maxdays, opzd.zip_archive_name, opzd.orders_products_zip_filename, opzd.zipfile_created  from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS_ZIP_DOWNLOAD . " opzd where o.customers_id = '" . $customer_id . "' and o.orders_id = '" . (int)$_REQUEST['order'] . "' and o.orders_id = opzd.orders_id and opzd.orders_products_zip_download_id = '" . (int)$_REQUEST['id'] . "' and opzd.orders_products_zip_filename != ''");
  if (!tep_db_num_rows($zipdownloads_query)) die;
  while( @ob_end_clean() );
  $zipdownloads = tep_db_fetch_array($zipdownloads_query);
// If this is the first time they download the ZIP file, create it
	  
  if ($zipdownloads['zipfile_created'] != 0) {
     // For testing purposes. Do not uncomment to get appropriate headers
	 // echo "zip file found: " . $zipdownloads['orders_products_zip_filename'] . ' with description: ' . $zipdownloads['zip_archive_name'] . '<br>';
	 $zip_file_exists = true;
	 $archive_name = $zipdownloads['orders_products_zip_filename'];
  } else {
     // For testing purposes. Do not uncomment to get appropriate headers
     // echo "No zip file found<br>";
	 $zip_file_exists = false;
     require_once(ZIP_COMPRESS_LIBRARY);
     $zip_file_list = "";
     // How to name the file?
	 $archive_name = tep_random_name() . '.zip';
	 $archive = new PclZip(DIR_FS_DOWNLOAD . $archive_name);

     $downloads_query = tep_db_query("select date_format(o.date_purchased, '%Y-%m-%d') as date_purchased_day, opd.download_maxdays, op.products_name, opd.orders_products_download_id, opd.orders_products_filename, opd.download_count, opd.download_maxdays from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS_PRODUCTS_DOWNLOAD . " opd where o.customers_id = '" . (int)$customer_id . "' and o.orders_id = '" . (int)$order . "' and o.orders_id = op.orders_id and op.orders_products_id = opd.orders_products_id and opd.orders_products_filename != ''");
	 $first_entry_read = false;
     if (tep_db_num_rows($downloads_query) > 0) {
		while ($downloads = tep_db_fetch_array($downloads_query)) {
		   // Keep track of earliest deadline of all downloads and use that as zip file time deadline
		   // Keep track of minimum number of downloads for all products and use that as zip file's man_downloads
		   if (!$first_entry_read) {
			 $min_download_days = $downloads['download_maxdays'];
			 $min_download_count = $downloads['download_count'];
			 $first_entry_read = true;
		   } else { 
			 if ($downloads['download_maxdays'] < $min_download_days) $min_download_days = $downloads['download_maxdays'];
			 if ($downloads['download_count'] < $min_download_count) $min_download_count = $downloads['download_count'];
		   }
			 				 
           // Add: Zip compression of downloadable products
           $zip_file_list .= $downloads['products_name'].'<br>';
		   $downloadfilenameforzip = DIR_FS_DOWNLOAD . $downloads['orders_products_filename'];
	
		   set_time_limit(10);
		   // Call the zipping utility 
		   $v_list = $archive->add(DIR_FS_DOWNLOAD . $downloads['orders_products_filename'], PCLZIP_OPT_REMOVE_ALL_PATH);
	    } // end while

	    // Now we get to update the database with the new found info
	    tep_db_query("update " . TABLE_ORDERS_PRODUCTS_ZIP_DOWNLOAD . " set orders_products_zip_filename = '" . $archive_name . "', download_maxdays = " . $min_download_days . ", download_count = " . $min_download_count . ", zipfile_created = 1 where orders_products_zip_download_id = ". (int)$_REQUEST['id']);

     } // end if downloadable products
	  
  } // End if create zip file

// Re-query the database in case things changed
// Check that order_id, customer_id and filename match
  $zipdownloads_query = tep_db_query("select date_format(o.date_purchased, '%Y-%m-%d') as date_purchased_day, opzd.download_maxdays, opzd.download_count, opzd.download_maxdays, opzd.zip_archive_name, opzd.zipfile_created  from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS_ZIP_DOWNLOAD . " opzd where o.customers_id = '" . $customer_id . "' and o.orders_id = '" . (int)$_REQUEST['order'] . "' and o.orders_id = opzd.orders_id and opzd.orders_products_zip_download_id = '" . (int)$_REQUEST['id'] . "' and opzd.orders_products_zip_filename != ''");
  if (!tep_db_num_rows($zipdownloads_query))  die;
  $zipdownloads = tep_db_fetch_array($zipdownloads_query);

// MySQL 3.22 does not have INTERVAL
  list($dt_year, $dt_month, $dt_day) = explode('-', $zipdownloads['date_purchased_day']); 
  $zipdownload_timestamp = mktime(23, 59, 59, $dt_month, $dt_day + $zipdownloads['download_maxdays'], $dt_year);

// Die if time expired (maxdays = 0 means no time limit)
  if (($zipdownloads['download_maxdays'] != 0) && ($zipdownload_timestamp <= time())) {
    echo "Your Zip download file time has expired<br>";
    // Remove file
	unlink (DIR_FS_DOWNLOAD . $archive_name);
    die;
  }

// Die if remaining count is <=0
  if ($zipdownloads['download_count'] <= 0) {
    echo "Your have reached the maximum number of downloads for this Zip file<br>";
    // Remove file
	unlink (DIR_FS_DOWNLOAD . $archive_name);
    die;
  }
  
// Die if file is not there
  if (!file_exists(DIR_FS_DOWNLOAD . $archive_name)) {
   echo "File does not exist!<br>";
   die;
  }

// Now decrement counter
  tep_db_query("update " . TABLE_ORDERS_PRODUCTS_ZIP_DOWNLOAD . " set download_count = download_count-1 where orders_products_zip_download_id = " . (int)$_REQUEST['id']);
  

// Returns a random name, 16 to 20 characters long
// There are more than 10^28 combinations
// The directory is "hidden", i.e. starts with '.'
function tep_random_name()
{
  $letters = 'abcdefghijklmnopqrstuvwxyz';
  $dirname = '.';
  $length = floor(tep_rand(16,20));
  for ($i = 1; $i <= $length; $i++) {
   $q = floor(tep_rand(1,26));
   $dirname .= $letters[$q];
  }
  return $dirname;
}

// Unlinks all subdirectories and files in $dir
// Works only on one subdir level, will not recurse
function tep_unlink_temp_dir($dir)
{
  $h1 = opendir($dir);
  while ($subdir = readdir($h1)) {
// Ignore non directories
    if (!is_dir($dir . $subdir)) continue;
// Ignore . and .. and CVS
    if ($subdir == '.' || $subdir == '..' || $subdir == 'CVS') continue;
// Loop and unlink files in subdirectory
    $h2 = opendir($dir . $subdir);
    while ($file = readdir($h2)) {
      if ($file == '.' || $file == '..') continue;
      @unlink($dir . $subdir . '/' . $file);
    }
    closedir($h2); 
    @rmdir($dir . $subdir);
  }
  closedir($h1);
}

// Now send the file with header() magic
while( @ob_end_clean() );
  header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
  header("Last-Modified: " . gmdate("D,d M Y H:i:s") . " GMT");
  header("Cache-Control: no-cache, must-revalidate");
  header("Pragma: no-cache");
  header("Content-Type: Application/octet-stream");
  header("Content-disposition: attachment; filename=VWarchive.zip"); // Be sure to add a .zip extension here
  header("Content-Length: " . filesize(DIR_FS_DOWNLOAD . $archive_name));	

  if (DOWNLOAD_BY_REDIRECT == 'true') {
// This will work only on Unix/Linux hosts
    tep_unlink_temp_dir(DIR_FS_DOWNLOAD_PUBLIC);
    $tempdir = tep_random_name();
    umask(0000);
    mkdir(DIR_FS_DOWNLOAD_PUBLIC . $tempdir, 0777);
    symlink(DIR_FS_DOWNLOAD . $archive_name, DIR_FS_DOWNLOAD_PUBLIC . $tempdir . '/' . $archive_name);
    tep_redirect(DIR_WS_DOWNLOAD_PUBLIC . $tempdir . '/' . $archive_name);
  } else {
// This will work on all systems, but will need considerable resources
// We could also loop with fread($fp, 4096) to save memory
    readfile(DIR_FS_DOWNLOAD . $archive_name);
  }

?>
